package com.banzhi.shop.activity;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.banzhi.shop.MyApp;
import com.banzhi.shop.R;
import com.banzhi.shop.base.BaseActivity;
import com.banzhi.shop.entity.Login.Login_data;
import com.banzhi.shop.entity.NewLogin.LoginModelImpl;
import com.banzhi.shop.model.CallBack.LoginModelCallBack;
import com.banzhi.shop.utils.ASUtils;
import com.banzhi.shop.utils.LoadingDialogUtils;
import com.banzhi.shop.utils.LogUtils;
import com.banzhi.shop.utils.ToastUtils;
import com.banzhi.shop.utils.Translucent;
import com.mob.tools.utils.UIHandler;

import org.json.JSONObject;

import java.util.HashMap;
import java.util.Set;

import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.api.TagAliasCallback;
import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.wechat.friends.Wechat;

import static com.banzhi.shop.MyApp.BlackTiShi;
import static com.banzhi.shop.MyApp.context;
import static com.banzhi.shop.MyApp.isBlackName;

public class NewLoginActivity extends BaseActivity implements View.OnClickListener,LoginModelCallBack,Handler.Callback, PlatformActionListener {

    private Button mBtnWeiXinLogin;
    private Button mBtnPhoneLogin;
    private LinearLayout mLlMimaLogin;
    private LinearLayout mLlYanzhengmaLogin;
    private LoginModelImpl mModel;


    //微信登录
    private Platform plat;
    private static final int MSG_AUTH_CANCEL = 1;
    private static final int MSG_AUTH_ERROR = 2;
    private static final int MSG_AUTH_COMPLETE = 3;
    private Handler handler;
    //这为什么等于空 明明有值啊
    private String openid = "";
    private ImageView mIvBackLogin;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        //启动Activity时不自动弹出软件盘
        getWindow().setSoftInputMode( WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN );
        super.onCreate( savedInstanceState );
        setContentView( R.layout.activity_new_login);
        Translucent.setTranslucent( this );
        ShareSDK.initSDK(this, "1dc05ab16fd6c");
        initView();
        setListener();
        handler = new Handler( this );
        mModel = new LoginModelImpl();

        if (isBlackName==1) {
            nopasslogin();
        }
        if (isBlackName == 2) {
            if (ASUtils.isCanUse(BlackTiShi)) {
                ToastUtils.makeToastShort(BlackTiShi);
            }
        }

    }

    private void nopasslogin() {
        if (!"".equals( MyApp.loginMessage.getString("token", ""))) {
            Intent intent = new Intent(NewLoginActivity.this, MainActivity.class);
            startActivity(intent);
            finish();
        }
    }

    //初始化控件
    private void initView() {
        mBtnWeiXinLogin = (Button) findViewById( R.id.bt_yanzhengma_login );
        mBtnPhoneLogin = (Button) findViewById( R.id.btn_phone_login );
        mLlMimaLogin = (LinearLayout) findViewById( R.id.ll_mima_Login );
        mLlYanzhengmaLogin = (LinearLayout) findViewById( R.id.ll__weixin_login );
        mIvBackLogin = (ImageView) findViewById(R.id.iv_back_login);

    }
    //监听控件
    private void setListener() {
        mBtnWeiXinLogin.setOnClickListener( this );
        mBtnPhoneLogin.setOnClickListener( this );
        mLlMimaLogin.setOnClickListener( this );
        mLlYanzhengmaLogin.setOnClickListener( this );
        mIvBackLogin.setOnClickListener(this);

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.bt_yanzhengma_login://改为验证码登陆
                Intent intent3 = new Intent( NewLoginActivity.this, YanzhengmaLoginActivity.class );
                startActivity( intent3 );
                break;
            case R.id.btn_phone_login:
                Intent intent = new Intent( NewLoginActivity.this, PhoneLoginActivity.class );
                startActivity( intent );
                break;
            case R.id.ll_mima_Login:
                Intent intent2 = new Intent( NewLoginActivity.this, MimaLoginActivity.class );
                startActivity( intent2 );
                break;
            case R.id.ll__weixin_login://改为微信登陆
                LoadingDialogUtils.showProgress( this,"正在加载中,请稍后" );
                // WXLogin( Wechat.NAME );
                WeChatLogin();

                break;
            case R.id.iv_back_login:
                    finish();
                break;
        }

    }


    private void WeChatLogin() {
        Platform weixinfd = ShareSDK.getPlatform(Wechat.NAME);
        weixinfd.setPlatformActionListener(this);
        if (weixinfd.isValid ()){
            weixinfd.removeAccount();
        }
        Log.d("LOGIN", "weixinfd.showUser");
        weixinfd.showUser(null);


    }

    @Override
    public void onloginSuccess(Object object) {

    }

    @Override
    public void onloginError(Object object) {

    }


    /**
     * @param object 微信登录成功
     */
    @Override
    public void onWXloginSuccess(Object object) {
        Login_data login = (Login_data) object;
        ToastUtils.makeToastShort("登录成功");
        Log.d("onWXloginSuccess: ",login.toString());
        SharedPreferences.Editor editor = MyApp.loginMessage.edit();
        editor.putString("token", login.getToken());
        editor.putString("id", login.getId());
        editor.putString("nickname", login.getNickname());
        editor.putString("openid_wx", login.getOpenid_wx());
        editor.putString("openid", login.getOpenid());
        editor.putString("mobile", login.getMobile());
        editor.putString("isagent",login.getIsagent()+"");
        editor.apply();
        Intent intent = new Intent(this, MainActivity.class);
        startActivity(intent);
        finish();

        //设置别名
        JPushInterface.setAlias(context,login.getMobile() ,
                new TagAliasCallback() {

                    @Override
                    public void gotResult(int responseCode,
                                          String alias, Set<String> tags) {
                        if (responseCode==0) {
                            System.out.println("jpush alias@@@@@别名设置成功");
                        }
                    }
                });


    }

    /**
     * @param object 微信登录失败
     */
    @Override
    public void onWXloginError(Object object) {
        LoadingDialogUtils.dismiss();
        JSONObject object1 = (JSONObject) object;
        ToastUtils.makeToastShort(object1.optString("msg"));
    }

    @Override
    public void onBindingPhoneSuccess(Object object) {

        Intent intent = new Intent(this, BindingLoginActivity.class);
        intent.putExtra( "Openid_wx",openid);
        startActivity(intent);
        finish();
    }

    @Override
    public void onYZMloginSuccess(Object object) {

    }

    @Override
    public void onYZMloginError(Object object) {

    }

    @Override
    public void onBindingLoginSuccess(Object object) {


    }

    @Override
    public void onBindingLoginError(Object object) {


    }

    public void onDestroy() {
        super.onDestroy();
        //停止shareSDK
        ShareSDK.stopSDK(this);
    }

    /**
     * 微信登录回调
     * @param platform
     * @param action
     */
    @Override
    public void onCancel(Platform platform, int action) {
        Message msg = new Message();
        msg.what = MSG_AUTH_CANCEL;
        msg.arg1 = 1;
        msg.arg2 = action;
        msg.obj = platform;
        UIHandler.sendMessage(msg, this);
    }

    @Override
    public void onComplete(Platform platform, int action, HashMap<String, Object> res) {
        Message msg = new Message();
        msg.what = MSG_AUTH_COMPLETE;
        msg.arg1 = 3;
        msg.arg2 = action;
        System.out.println(res);
        //获取资料
        String nickname = platform.getDb().getUserName();//获取用户名字
        String iconUri = platform.getDb().getUserIcon(); //获取用户头像
        platform.getDb().get("openid");
        String openid =platform.getDb().getUserId();
        String token = platform.getDb().getToken();
/*        String refresh_token111 = platform.getDb().get("refresh_token");
        String toJSLogin = "{" +
                "  \"headimgurl\" : \"" + iconUri + "\","
                + "  \"nickname\" : \"" + nickname + "\","
                + "  \"openid\" :  \""+ openid + "\""
                + "}";
        Log.d("WXCHATLOGIN", toJSLogin);*/
        msg.obj = res;
        UIHandler.sendMessage(msg, this);

    }

    @Override
    public void onError(Platform platform, int action, Throwable t) {
        t.printStackTrace();

        Message msg = new Message();
        msg.what = MSG_AUTH_ERROR;
        msg.arg1 = 2;
        msg.arg2 = action;
        msg.obj = t;
        UIHandler.sendMessage(msg, this);

        // 分享失败的统计
     //   ShareSDK.logDemoEvent(4, platform);
    }
    @Override
    public boolean handleMessage(Message msg) {
        switch (msg.what) {
            case MSG_AUTH_COMPLETE:
                // 成功
                HashMap<String, Object> map = (HashMap<String, Object>) msg.obj;
                try {
                    //这里赋值了
                    openid = map.get("openid").toString();
                    LogUtils.d( "openid:", openid);
                    mModel.WXlogin(openid, this);

                } catch (Exception e) {
                    ToastUtils.makeToastShort("数据异常");
                }

                break;
        }
        return false;
    }
}
/*    private void WXLogin(String name) {
      Log.d("WXLogin ","WXLogin");
        plat = ShareSDK.getPlatform(name);
     if (plat == null) {
            LoadingDialogUtils.dismiss();
            return;
        }

        if (plat.isAuthValid()) {
            plat.removeAccount(true);
            LoadingDialogUtils.dismiss();
            return;
        }

        //使用SSO授权，通过客户单授权
        plat.SSOSetting(false);
        if (!plat.isClientValid()) {
            ToastUtils.makeToastShort("微信未安装，请先安装微信");
            LoadingDialogUtils.dismiss();
        }




    *//*    plat.setPlatformActionListener(new PlatformActionListener() {
            @Override
            public void onComplete(final Platform platform, final int i, final HashMap<String, Object> res) {
                Log.i("sss",platform.getDb().exportData());

                Log.i("sss",res.toString());

                new Thread(new Runnable() {

                    @Override
                    public void run() {
                        Looper.prepare();

                        Message msg = new Message();
                        msg.what = MSG_AUTH_COMPLETE;
                        msg.arg2 = i;
                        msg.obj = res;
                        System.out.println(res);
                        //获取资料
                        String nickname = platform.getDb().getUserName();//获取用户名字
                        String iconUri = platform.getDb().getUserIcon(); //获取用户头像
                        platform.getDb().get("openid");
                        String openid =platform.getDb().getUserId();
                        String token = platform.getDb().getToken();
                        handler.sendMessage(msg);
                                     *//**//*  //       if (i == Platform.ACTION_USER_INFOR) {}
                            LoadingDialogUtils.dismiss();
                            Message msg = new Message();
                            msg.what = MSG_AUTH_COMPLETE;
                            msg.arg2 = i;
                            msg.obj = res;
                            handler.sendMessage(msg);*//**//*


                        Toast.makeText(NewLoginActivity.this, "成功了", Toast.LENGTH_SHORT).show();
                        Looper.loop();
                    }
                }).start();

            }
            @Override
            public void onError(Platform platform, int i, Throwable throwable) {
                Log.i("sss",throwable.toString());
            }

            @Override
            public void onCancel(Platform platform, int i) {
                Log.i("sss","onCancel");


            }
        });*//*

        //   plat.authorize();
        // true不使用SSO授权，false使用SSO授权
        plat.SSOSetting(false);
        plat.showUser(null);


    }*/